<?php
namespace app\admin\controller;

use app\admin\model\Task as TaskModel;
use app\admin\model\TaskUser as TaskUserModel;
use app\admin\model\Account as AccountModel;
use app\admin\model\ImageLibrary as ImageLibraryModel;
use app\admin\model\VideoLibrary as VideoLibraryModel;
use app\admin\model\Device as DeviceModel;
use app\admin\org\HttpRequest;

class Receipt extends Base
{
    public function index()
    {
        $model = new TaskUserModel;
        $Tmodel = new TaskModel;
        $Umodel = new AccountModel;

        //渲染页面模板
        $model->field('m.task_id,m.user_id,m.content,m.receive_at,m.submit_at,m.status,m.conclusion,
        t.name as tname,u.username')
            ->alias('m')
            ->join('task t','m.task_id = t.id ','left')
            ->join('user u','m.user_id = u.id','left')
            ->where('m.status', '>', '0')
            ->order('m.receive_at','desc');
        // ->select();
        //->paginate(5);

        //搜索名称
        $phname = $this->request->param("phname");

        if(!empty($phname)){
            $model->where('t.name','like', '%'.$phname.'%');
        }
        $result = $model->paginate(10,false,[
            'query'=>['phname'=>$phname]
        ]);

        //计算总共记录条数
        $count = $result->total();
        //分页
        $page = $result->render();

        //渲染用户组
        $task = $Tmodel->field('id,name')->select();
        $user = $Umodel->field('id,username')->select();

        //接收ajax传递的值
        $request = request();
        $ispost = $request->isPost();
        if($ispost){
            $taskid = $_POST["taskId"];
            $userid = $_POST["userId"];
            $view = $model->getAll()->where(["task_id"=>$taskid,"user_id"=>$userid])->find();
            return json([
                'code' => 200,
                'view'=>$view,
            ]);
        }

        $this->assign('currentPage',$result->currentPage());
        $this->assign('lastPage',$result->lastPage());
        $this->assign('page',$page);
        $this->assign('taskuser',$result);
        $this->assign('task',$task);
        $this->assign('user',$user);
        $this->assign('count',$count);
        $this->assign('empty',"暂无数据");
        return $this->fetch();
    }

    public function view($taskid,$userid)
    {
        //临时设置上传的最大时间
        ini_set("max_execution_time",0);
        $model = new TaskUserModel;
        $Accountmodel = new AccountModel;
        $answer = $model->field("answer")->where(['user_id'=>$userid,'task_id'=>$taskid])->whereNull("deleted_at")->find();

        $VideoLibrarymodel = new VideoLibraryModel;
        $ImageLibrarymodel = new ImageLibraryModel;
        //截取字符串
        if (empty($answer["answer"])) {
            return json([
                'code' => 200,
                'msg' => "暂无数据"
            ]);
        }

        $answerArr = explode(",",$answer["answer"]);
        //拼接字符串给每个文件名加上引号
        $inStr = array_map(function ($res) {
            return '"'.$res.'"';
        }, $answerArr);

        //包含点的后缀名
        $ext = strrchr($answerArr[0],".");
        $urlArr = [];

        switch($ext){
            case ".jpg":
                //云盘数据类型
                $type="/capture";
                $urlArr = $ImageLibrarymodel
                    ->field("title, server_url")
                    ->where('title', "exp","in (". implode(',', $inStr) .")")
                    ->whereNull("deleted_at")
                    ->select();
               //var_dump(ImageLibrary::getLastSql());
                break;
            case ".mp4":
                //云盘数据类型
                $type="/lock";
                $urlArr = $VideoLibrarymodel
                    ->field("title, server_url")
                    ->where(['user_id'=>$userid])
                    ->where('title', "exp","in (". implode(',', $inStr) .")")
                    ->whereNull("deleted_at")
                    ->select();
               //var_dump(VideoLibraryModel::getLastSql());
                break;
            case ".ts":
                //云盘数据类型
                $type="";
                $urlArr = $VideoLibrarymodel
                    ->Field("title,server_url")
                    ->where(['user_id'=>$userid])
                    ->where('title', "exp","in (". implode(',', $inStr) .")")
                    ->whereNull("deleted_at")
                    ->select();
                //var_dump(VideoLibraryModel::getLastSql());
                break;
        }

        $titleArr = array_column($urlArr, 'title');

        $diffArr = array_diff($answerArr, $titleArr);

        if(empty($diffArr)){
            return json([
                'code' => 200,
                'data'=>["list"=>$urlArr]
            ]);
        }
        //查找用户的用户名密码 去云盘下载
        $Accountdata = $Accountmodel->field("username, password,password2")->where(['id'=>$userid])->whereNull("deleted_at")->find();
       //$Accountdata = ["username"=>"15800715040","password"=>"123456","password2"=>"abc123456abc"];
        $Accountdata['base64_username'] = base64_encode($Accountdata['username']);

        $originPassword = substr($Accountdata['password2'], 3, -3);

        $imeiArr = DeviceModel::where('user_id', $userid)->column('imei');
        //$imeiArr = ["53810053839"];

        $files = [];
        $agent = \think\Config::get('clouddisk.agent');
        foreach ($imeiArr as $key => $imei) {
            // 从云盘中获取文件
            $res = $this->_cloudDisk($imei . $type, $Accountdata['username'], $originPassword);

            // 只有一个设备， 并且目录不存在，直接返回空数组；
            if ($res['code'] !== 200 && count($imeiArr) === 1) {
                // return $this->jmReturnJson(4002, $res['message']);
                return json([
                    'code'=>200,
                    'message'=>'暂无数据',
                    'data'=>['list' => []]
                ]);
            }

            // $key1 是文件名，比如 "/remote.php/webdav/test/HSBCnet.mp4"；
            // $value 是文件属性的数组，比如
            /* array(5) {
                //["{DAV:}getcontentlength"]=> string(8) "40139260"
                ["{DAV:}getcontenttype"]=> string(9) "video/mp4"
                //["{DAV:}getetag"]=> string(34) ""7da2b6b38585f2d804f80434af34a935""
                ["{DAV:}getlastmodified"]=> string(29) "Sun, 24 Mar 2019 09:58:30 GMT"
                //["{DAV:}resourcetype"]=> NULL
            }
            其中，只有 "{DAV:}getcontenttype" 和 "{DAV:}getlastmodified" 有意义；
            而且，返回的数据是按文件名排序的， 并不是按创建时间倒序；
            */
            if (isset($res['data'])) {
                foreach ($res['data'] as $key1 => $value) {
                    // 去除目录，比如当前目录本身，以及可能的 lock 目录；
                    if (isset($value['{DAV:}getcontenttype'])) {
                        //$subname = substr(strrchr($key1,"/"),1);
                        $basename = basename($key1);
                        if(in_array($basename, $diffArr)){
                            array_push($files, [
                                'userId' => $userid,
                                'userdata' => $Accountdata["username"] . ":" . $originPassword,
                                'imei' => $imei,
                                'filename' => $basename,
                                //'url' => 'http://58.57.117.132:9801' . $key,
                                'url' => $agent . $Accountdata['base64_username'] . '/' . $Accountdata['password'] . '/' . $imei . $type . '/' . $basename,
                            ]);
                        }
                    }
                }
            }

            $fileData = [];
            foreach ($files as $k=>$v){
                $content = HttpRequest::download("https://cloud.leeker.cc:1443/remote.php/webdav/".$imei.$type.'/'.$files[$k]["filename"],null,$files[$k]["userdata"]);
                $file_dir = ROOT_PATH . 'public/static/clouddisk/'.$files[$k]["filename"];    // 下载文件存放目录
                //$server_url = '/static/clouddisk/'.$files[$k]["filename"];
                file_put_contents($file_dir, $content);
                $filename2 = str_replace(strrchr(basename($files[$k]["filename"]), '.'), '', basename($files[$k]["filename"]));
                $playurl = '/static/clouddisk/'.$filename2.$ext;
                if ($ext==".jpg") {
                    // 图片
                    // 保存
                    $result = $ImageLibrarymodel->save(['user_id'=>$userid,'server_url'=>$playurl,'title'=>$files[$k]["filename"]]);
                } else {
                    // 视频
                    // ts转码
                    if($ext==".ts"){
                        //php转码ts视频文件
                        //exec('D:/ffmpeg-20190812-9fdc7f1-win64-static/bin/ffmpeg.exe  -i  '.$file_dir.' '.ROOT_PATH . 'public/static/clouddisk/'.$filename2.'.mp4');//-c:v libx264 -strict -2
                        exec('ffmpeg  -i '.$file_dir.' '.ROOT_PATH . 'public/static/clouddisk/'.$filename2.'.mp4');//-c:v libx264 -strict -2
                        $playurl = '/static/clouddisk/'.$filename2.'.mp4';
                    }
                    // 保存
                    $result = $VideoLibrarymodel->save(['user_id'=>$userid,'server_url'=>$playurl,'title'=>$files[$k]["filename"]]);
                }
                if(!$result){
                    return json([
                        'code' => 4001,
                        'msg'=>"数据添加失败",
                    ]);
                }
                array_push($fileData, [
                    'title' => $files[$k]["filename"],
                    'server_url' => $playurl
                ]);
            }

            return json([
                'code' => 200,
                'data' => ["list"=>array_merge($urlArr, $fileData)]
            ]);
        }
    }

    // 每个用户的行车记录仪上传的文件在该设备的imei为目录名称的目录下
    private function _cloudDisk($imei, $username, $password) {
        try {
            $url = \think\Config::get('clouddisk.domain') . 'remote.php/webdav/' . $imei;
            $settings = array(
                'baseUri' => $url,
                'userName' => $username,
                'password' => $password
            );
            $client = new \Sabre\DAV\Client($settings);

            $response = $client->propFind($url, array(
                // $response = $client->propFind('collection', array(
                // '{DAV:}getcontentlength',
                '{DAV:}displayname',
                '{DAV:}getcontenttype',
                // '{DAV:}getetag',
                // '{DAV:}getlastmodified'
            ), 1);
            // 当访问不存在的目录时，直接被catch了，下面这个 var_dump 不会执行；

            return ['code'=>200, 'data'=>$response];
        } catch (\Exception $e) {
            return [
                'code' => 4000,
                'message'=>$e->getMessage()
            ];
        }
    }

    public function edit($taskid,$userid)
    {
        $model = new TaskUserModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();

        if($ispost){
            $formdata = $this->request->post();

            $result = $model->allowField(true)->save($formdata,['task_id'=>$taskid,'user_id'=>$userid]);

            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //删除单条记录
    public function delete($taskid,$userid)
    {
        $result = TaskUserModel::update(['deleted_at'=>date('Y-m-d H:i:s')],['task_id'=>$taskid,'user_id'=>$userid]);//软删除

        if($result){
            return json([
                'code' => 200,
            ]);
        }

    }

    //批量删除
    public function deleteArr()
    {
        $ispost = $this->request->isPost();
        if ($ispost) {
            $idArr = $this->request->post();

            $result = TaskUserModel::where('task_id','exp','in('.implode(',',$idArr['id']).')')->update(['deleted_at'=>date('Y-m-d H:i:s')]);//软删除

            if($result){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //审核任务
    public function examine($taskid,$userid)
    {
        $model = new TaskUserModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();

        if($ispost){
            $formdata = $this->request->post();

            $result = $model->allowField(true)->save($formdata,['task_id'=>$taskid,'user_id'=>$userid]);

            if($result){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }
}